<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      #btn01 {
        width: 1000px;
        height: 1000px;
        margin: auto auto;
      }
    </style>
    <script>
      window.onload = function () {
        var imgArray = [
          'img/1.jpg',
          'img/2.jpg',
          'img/3.jpg',
          'img/4.jpg',
          'img/5.jpg',
        ];

        var img01 = document.getElementById('img01');
        var stop = document.getElementById('stop');
        var start = document.getElementById('start');

        var num = 0;

        //定义一个变量，用来保存定时器的标识
        var timer;

        start.onclick = function () {
          /*
           * 目前，我们每点击一次按钮，就会开启一个定时器，
           * 	点击多次就会开启多个定时器，这就导致图片的切换速度过快，
           * 	并且我们只能关闭最后一次开启的定时器
           */

          //在开启定时器之前，需要将当前元素上的其他定时器关闭
          clearInterval(timer);
          temir = setInterval(function () {
            img01.src = imgArray[num++];
            if (num >= imgArray.length) {
              num = 0;
            }
          }, 1000);
        };

        stop.onclick = function () {
          clearInterval(temir);
        };
      };
    </script>
  </head>
  <body>
    <div id="btn01">
      <img id="img01" src="img/1.jpg" />
      <br />
      <br />
      <button id="stop">停止</button>
      <button id="start">开始</button>
    </div>
  </body>
</html>
